<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_block_TabPagePropertiesAction extends m_backoffice_extends_Action
{
	public function execute()
	{
        $documentId = $this->getBlockContext()->getParameter("documentId", $this->getRequestParameter("docId"));
		$documentLang = $this->getBlockContext()->getParameter("documentLang", $this->getRequestParameter("docLang"));
        $tempService = m_backoffice_services_TempDocService::getInstance();

        // Get the page to save properties from db
		if(!is_null($documentId))
		{
			$page = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $documentId, $documentLang);
            $tmpPage = $tempService->getTemporaryDocument($documentId, $documentLang);
		}

        if(!is_null($page->getRight()) && $page->getRight() != '')
        {
            $errorPages = f_target_Manager::getDocumentsByTarget('401', $page->getLang());
            $this->addToModel("errorPages", $errorPages);

            $rightUsers = explode(' ', $page->getRight());

            foreach($rightUsers as $userId)
            {
                $users[] = $this->getDocumentProvider()->getByUniqueId($userId);
            }
            $this->addToModel('users', $users);
        }

		$formValues = $this->getFormValues("form");

		if(count($formValues) > 0)
		{
            $page401 = isset($formValues["page401"]) ? $formValues["page401"] : null;
            
			$errors = $this->checkForm($formValues, $page);
            /* @var $page m_website_documents_Page */
			$page	->setLabel($formValues["label"])
					->setUrl("/".$formValues["url"])
					->setMetaTitle($formValues["metaTitle"])
					->setMetaKeywords($formValues["metaKeywords"])
					->setMetaDescription($formValues["metaDescription"])
					->setMenuLabel($formValues["menuLabel"])
					->setVisibleInMenu($formValues["visibleInMenu"])
					->setMenuHoverLabel($formValues["menuHoverLabel"])
                    ->setPage401($page401)                    
                    ->setInSiteMap($formValues["inSiteMap"])
                    ->setIndexable($formValues["isIndexable"]);

            if($formValues["template"] != $page->getParentTemplate())
            {
                if($tempService->hasTemporary($page->getUniqueId(), $page->getLang()))
                {
                    $tempPage = $tempService->getTemporaryDocument($page->getUniqueId(), $page->getLang());
                    $tempPage->setTemplate($formValues['template']);
                    $tempService->saveTemporaryDocument($tempPage);
                }
                else
                {
                    $page2 = $page->cloneDocument()->setTemplate($formValues['template']);
                    $tempService->saveTemporaryDocument($page2);
                }
            }

			if(count($errors) > 0)
			{				
				if($errors["url"] == "copy")
				{
					$page->setSwitch(true);
					$orig = $this->getDocumentProvider()->loadDocuments("modules_website/Page")
														->byPublicationStatus("PUBLISHED")
														->whereIsEqual("url", "/".$formValues["url"])
														->whereIsEqual("websiteId", $page->getWebsiteId())
														->retrieveFirstDocument();
					$page->setPageToSwitch($orig);	
				}

				$errors["status"] = "failed";
				$this->addToModel("errors", $errors);
			}
			else
			{			
                if(isset($formValues["forceSwitch"]) && $formValues["forceSwitch"] == "on")
                {
                    $oldPage = $this->getDocumentProvider()->loadDocuments("modules_website/Page")
                                                ->whereIsEqual("document_publicationstatus", "PUBLISHED")
                                                ->whereIsEqual("url", "/".$formValues["url"])
                                                ->whereIsEqual("websiteId", $page->getWebsiteId())
                                                ->whereIsNotEqual("document_uid", $page->getUniqueId())
                                                ->retrieveFirstDocument($page->getLang());

                    $menu = $oldPage->getIndexMenu();

                    if(!is_null($menu))
                    {
                        $menu->setMenuPageId($page->getUniqueId())->save(false);
                    }

                    if(!is_null($oldPage))
                    {
                        $oldPage->setPublicationStatus("DRAFT")->save(false);
                    }
                }

                $page->setAuthor($this->getUser()->getLogin())->save(false);
			}
		}
        else
        {
            $formValues = $this->getFormParamsFromPage($page);
        }

        $layouts = m_website_services_PageService::getInstance()->getTemplates($page->getThemeName(), $this->getContext('currentWebsite'));

        $this->addToModel('templates', $layouts);
        $this->addToModel('page', $page);
        $this->addToModel('tmpPage', $tmpPage);
		$this->addToModel('formValues', $formValues);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "website_TabPageProperties"));
	}

    private function getFormParamsFromPage($page)
    {
        /* @var $page m_website_documents_page */
        $formValues['label'] = $page->getLabel();
        $formValues['url'] = $page->getFormattedUrl();
        $formValues['metaTitle'] = $page->getMetaTitle();
        $formValues['metaKeywords'] = $page->getMetaKeywords();
        $formValues['metaDescription'] = $page->getMetaDescription();
        $formValues['menuLabel'] = $page->getMenuLabel();
        $formValues['visibleInMenu'] = $page->isVisibleInMenu();
        $formValues['menuHoverLabel'] = $page->getMenuHoverLabel();
        $formValues['page401'] = $page->getPage401();
        $formValues['inSiteMap'] = $page->isInSiteMap();
        $formValues['isIndexable'] = $page->isIndexable();
        return $formValues;
    }
	
	private function checkForm($formValues, $page)
	{
		$errors = array();

		if($formValues["label"] == "")
		{
			$errors["label"] = $this->getLocale('website.errors.required');
		}
		
		if($formValues["metaTitle"] == "")
		{
			$errors["metatitle"] = $this->getLocale('website.errors.required');
		}		

		if("/".$formValues["url"] != $page->getUrl(true))
		{
			if(!preg_match("/^([a-zA-Z0-9\/.~_,-<>])*$/",$formValues["url"]))
			{
				$errors["url"] = $this->getLocale('website.errors.invalidUrlChar');
			}

            if(preg_match("/\/([0-9]+)\//", $formValues["url"]))
			{
				$errors["url"] = $this->getLocale('website.errors.invalidUrlFormat');
			}
			
			if(substr($formValues["url"],0, 1) == "/")
			{
				$errors["url"] = $this->getLocale('website.errors.invalidUrlBegin');
			}

			if($this->checkUrl($formValues["url"], $page) && isset($formValues["forceSwitch"]) && $formValues["forceSwitch"] != "on" && $page->getPublicationStatus() == 'PUBLISHED')
			{
				$errors["url"] = "copy";
			}
		}
		
		return $errors;
	}
	
	/**
	 * Check if url exist
	 * @return boolean
	 */
	private function checkUrl($url, $page)
	{
		return m_website_services_URLService::urlExists("/".$url, $page->getWebsiteId(), $this->getRequestParameter("docLang"));
	}
}